package org.blog.logic;

import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.blog.beans.Blog;
import org.blog.beans.Comment;
import org.blog.beans.User;
import org.blog.database.connection.ConnectionManager;
import org.blog.encryption.MD5;
import org.blog.exceptions.InvalidLoginException;
import org.blog.exceptions.InvalidMailException;
import org.blog.exceptions.InvalidPasswordException;
import org.blog.exceptions.LoginAlreadyExistsException;
import org.blog.exceptions.SettingsException;
import org.blog.tools.Expression;

public class UserLogic {

	static private UserLogic userLogic;
	

	public static final int LOGIN_MIN = 3;
	public static final int LOGIN_MAX = 20;
	public static final int PASS_MIN = 6;
	public static final int PASS_MAX = 20;
	public static final int MAIL_MAX = 45;
	
	static public UserLogic getInstance() {
		if (userLogic == null) {
			userLogic = new UserLogic();
		}
		return userLogic;
	}
	
	public void register(User user) throws LoginAlreadyExistsException, InvalidLoginException, 
							InvalidPasswordException, InvalidMailException {

		if(!isLoginValid(user.getLogin())) throw new InvalidLoginException();
		if(!isPasswordValid(user.getPassword())) throw new InvalidPasswordException();
		if(!isMailValid(user.getMail())) throw new InvalidMailException();

		Connection conn = ConnectionManager.getManager().getConnection();
		PreparedStatement st = null;
		ResultSet resultSet = null;
		try {
			
			st = conn.prepareStatement("select login from uzytkownicy where login = ?");
			
			st.setString(1, user.getLogin());
			
			resultSet = st.executeQuery();
			if(resultSet != null) {
				while(resultSet.next()) {
					if(user.getLogin().equals(resultSet.getString("login")))
						throw new LoginAlreadyExistsException();
				}
			}

			st = conn.prepareStatement("INSERT INTO uzytkownicy (imie, nazwisko, login, haslo, opis,  email)"
					+ " VALUES (?,?,?,?,?,?)");
			
			st.setString(1, user.getName());
			st.setString(2, user.getSurname());
			st.setString(3, user.getLogin());
			st.setString(4, MD5.encrypt(user.getPassword()));
			st.setString(5, user.getDescription());
			st.setString(6, user.getMail());

			st.executeUpdate();
			st.close();

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

	}
	public User getUser(int id) {
		
		User user = null;
		
		Connection conn = ConnectionManager.getManager().getConnection();
		PreparedStatement st = null;
		ResultSet resultSet = null;
		try {
			
			st = conn.prepareStatement("select * from uzytkownicy where idUzyt = ?");
			
			st.setInt(1, id);
			
			resultSet = st.executeQuery();
			if(resultSet != null) {
				if(resultSet.next()) {
					user = new User();
					initUser(user, resultSet);
				}
			}

			st.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return user;
	}
public User getUser(String login) {
		
		User user = null;
		
		Connection conn = ConnectionManager.getManager().getConnection();
		PreparedStatement st = null;
		ResultSet resultSet = null;
		try {
			
			st = conn.prepareStatement("select * from uzytkownicy where login = ?");
			
			st.setString(1, login);
			
			resultSet = st.executeQuery();
			if(resultSet != null) {
				if(resultSet.next()) {
					user = new User();
					initUser(user, resultSet);
				}
			}

			st.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return user;
	}
	public User login(User user) throws InvalidLoginException, InvalidPasswordException {

		if(!isLoginValid(user.getLogin())) throw new InvalidLoginException();
		if(!isPasswordValid(user.getPassword())) throw new InvalidPasswordException();
		
		Connection conn = ConnectionManager.getManager().getConnection();
		PreparedStatement st = null;
		ResultSet rs = null;
		
		User baseUser = null;
		
		try {
		
			st = conn.prepareStatement("select * from uzytkownicy where login = ?");
			
			st.setString(1, user.getLogin());
					
			rs = st.executeQuery();
			
			if(rs.next()) {
				baseUser = new User();
				initUser(baseUser, rs);
			} else 
				throw new InvalidLoginException();
				
			if(!MD5.encrypt(user.getPassword()).equals(baseUser.getPassword()))
				throw new InvalidPasswordException();
			
			
			st.executeQuery();
			st.close();
		
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		return baseUser;
		
	}
	public List<User> getUsers() {
		
		List<User> users = new ArrayList<User>();
		
		Connection conn = ConnectionManager.getManager().getConnection();
		PreparedStatement st = null;
		ResultSet resultSet = null;
		try {
			
			st = conn.prepareStatement("select * from uzytkownicy");
			
			resultSet = st.executeQuery();
			if(resultSet != null) {
				while(resultSet.next()) {
					User user = new User();
					initUser(user, resultSet);
					users.add(user);
				}
			}

			st.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return users;
	}
	public void delete(int userId) {
	
		Connection conn = ConnectionManager.getManager().getConnection();
		PreparedStatement st = null;
		try {
			
			st = conn.prepareStatement("delete from uzytkownicy where idUzyt = ?");			
			st.setInt(1, userId);
			st.executeUpdate();
			st.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			
			st = conn.prepareStatement("delete from blogi where idUzyt = ?");			
			st.setInt(1, userId);	
			st.executeUpdate();
			st.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
	public void update(User user) throws SettingsException, InvalidMailException {
		
		if(!Expression.isValid(user.getName(), 30, 0)) throw new SettingsException(SettingsException.NAME);
		if(!Expression.isValid(user.getSurname(), 30, 0)) throw new SettingsException(SettingsException.SURNAME);
		if(!Expression.isValid(user.getDescription(), 255, 0)) throw new SettingsException(SettingsException.DESCRIPTION);
		if(!isMailValid(user.getMail())) throw new InvalidMailException();
		
		Connection conn = ConnectionManager.getManager().getConnection();
		PreparedStatement st = null;
		
		try {
		
			st = conn.prepareStatement("UPDATE uzytkownicy SET imie = ?, nazwisko = ? , email = ?, opis = ?, styl = ?"
					+ "WHERE login = ?");
			
			st.setString(1, user.getName());
			st.setString(2, user.getSurname());
			st.setString(3, user.getMail());
			st.setString(4, user.getDescription());
			st.setString(5, user.getStyle());
			st.setString(6, user.getLogin());
					
			st.executeUpdate();
					
			st.close();
		
		} catch (SQLException e) {
			e.printStackTrace();
		} 
	}
	
	private static void initUser(User u, ResultSet rs) {		
		try {
			u.setId(rs.getInt("idUzyt"));
			u.setLogin(rs.getString("login"));
			u.setPassword(rs.getString("haslo"));
			u.setMail(rs.getString("email"));
			u.setName(rs.getString("imie"));
			u.setSurname(rs.getString("nazwisko"));
			u.setDescription(rs.getString("opis"));
			u.setStyle(rs.getString("styl"));
			
		} catch(SQLException e) {
			u = null;
		}
	}
	
	private static boolean isLoginValid(String login) {
		boolean valid = true;
		valid &= Expression.isRegular(login);
		valid &= login.length() >= LOGIN_MIN;
		valid &= login.length() <= LOGIN_MAX;
		return valid;
	}
	
	
	
	private static boolean isPasswordValid(String pass) {
		
		boolean valid = true;
		valid &= Expression.isRegular(pass);
		valid &= pass.length() >= PASS_MIN;
		valid &= pass.length() <= PASS_MAX;
		valid &= containsNumber(pass);
		return valid;
	}
	
	private static boolean isMailValid(String mail) {
		
		if(mail.length() > MAIL_MAX) return false;
		
		int i = mail.indexOf('@');
		if(i < 0) return false;
		
		String str = mail.substring(0, i-1);
		if(str.indexOf('.') == 0) return false;
		if(!Expression.isRegular(str)) return false;
		
		str = mail.substring(i+1, mail.length());
		if(str.indexOf('.') == 0) return false;
		if(str.endsWith(".")) return false;
		if(!Expression.isRegular(str) || !str.contains(".")) return false;
		
		return true;
	}
	
	
	
	private static boolean containsNumber(String string) {
		
		Pattern p = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(string);
		return m.find();
	}
	
	public static void main(String[] args) {
		
		/*
		User u = new User();
		u.setLogin("Maciej");
		u.setPassword("maciej1");

				
		try {
			System.out.println( UserLogic.getInstance().login(u).getLogin() );
		} catch (InvalidLoginException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidPasswordException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		*/


	}
}
